﻿using IConfiguration;
using IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Start.Controllers {
  [Route("api/[controller]")]
  [ApiController]
  public class UserController : ControllerBase {
    ILoginService _loginService;
    IMenuService _menuService;
    IUserService _userService;
    IUtils _utils;
    public UserController(ILoginService loginService,IMenuService menuService,IUserService userService,IUtils utils) {
      _loginService = loginService;
      _menuService = menuService;
      _userService = userService;
      _utils = utils;
    }
    [HttpPost]
    [Route("login")]
    public IActionResult Login([FromForm] string username,[FromForm] string password) {
      string pwd = _utils.GetMD5Str(_utils.GetMD5Str(password) + "|" + username);
      var users = _loginService.Query<SysUserInfo>(u => u.UserName == username && u.Password == pwd);
      if (users?.Count() > 0) {
        var userInfo = users.ToList();
        SysUserInfo sysUserInfo = userInfo[0];
        //获取用户菜单
        List<MenuInfo> menus = _menuService.GetMenusByUserId(sysUserInfo.UserId);
        sysUserInfo.Menus = menus;
        return Ok(sysUserInfo);
      } else {
        return NoContent();
      }
    }
    [HttpGet]
    [Route("all")]
    public IActionResult GetUsers() {
      return Ok(_userService.Query<SysUserInfo>(u => true));
    }
    [HttpGet("roles/{userId}")]
    public IActionResult GetRolesByUserId(int userId) {
      return Ok(_userService.GetRolesByUserId(userId));
    }
    [HttpPost]
    [Route("resetpwd")]
    public IActionResult ResetPassword([FromForm] IFormCollection form) {
      _userService.ResetPassword(int.Parse(form["userId"]));
      return Ok();
    }

    [HttpPost]
    [Route("save")]
    public IActionResult UpdateUserInfo([FromBody] JsonElement data) {
      _userService.SaveUser(data.ToString());
      return Ok(data);
    }

  }
}
